<template>
  <div class="main-content">
    <i-menu mode="horizontal"
            :active-name="activeName"
            style="margin-bottom: 10px;"
            @on-select="changeMenuSelect">
      <Menu-item name="1">
        在售楼盘（{{premisesTypeCount.onSaleCount}}）
      </Menu-item>
      <Menu-item name="2">
        待售楼盘（{{premisesTypeCount.forSaleCount}}）
      </Menu-item>
      <Menu-item name="3">
        待审核（{{premisesTypeCount.beCheckCount}}）
      </Menu-item>
      <Menu-item name="4"
                 class="gray-color">
        售罄楼盘（{{premisesTypeCount.sellOutCount}}）
      </Menu-item>
      <Menu-item name="5"
                 class="gray-color">
        下架楼盘（{{premisesTypeCount.lowerShelfCount}}）
      </Menu-item>
      <Menu-item name="6"
                 class="gray-color">
        审核不通过（{{premisesTypeCount.checkFailCount}}）
      </Menu-item>
    </i-menu>
    <div class="screen-frame clearfix">
      <div class="col-md-6 col-lg-6">
        <div class="form-horizontal">
          <div class="form-group">
            <label class="col-md-3 col-sm-2 control-label text-left">楼盘名称：</label>
            <div class="col-md-8 col-sm-10">
              <input type="text"
                     class="form-control"
                     placeholder="楼盘名称"
                     v-model="params.name">
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label class="col-md-3 col-sm-2 control-label">省份市区：</label>
            <div class="col-md-8 col-sm-10">
              <select class="form-control"
                      style="width:32%;float:left"
                      v-model="params.provinceId"
                      id="province"
                      v-on:change="getCity()">
                <option value="">全部</option>
                <option v-for="(province,index) in premises_province_list"
                        :value="province.id"
                        :key="index">{{province.name}}</option>
              </select>
              <span style="float:left">-</span>
              <select class="form-control"
                      style="width:32%;float:left"
                      v-model="params.cityId"
                      id="city"
                      v-on:change="getArea()">
                <option value="">全部</option>
                <option v-for="(city,index) in premises_city_list"
                        :value="city.id"
                        :key="index">{{city.name}}</option>
              </select>
              <span style="float:left">-</span>
              <select class="form-control"
                      style="width:32%;float:left"
                      v-model="params.areaId">
                <option value="">全部</option>
                <option v-for="(area,index) in premises_area_list"
                        :value="area.id"
                        :key="index">{{area.name}}</option>
              </select>
            </div>
          </div>
        </div>
        <!-- <div class="form-horizontal">
				<div class="form-group">
					<label class="col-md-3 col-sm-2 control-label">物业类型：</label>
					<div class="col-md-8 col-sm-10">
						<select class="form-control" v-model="params.estateType">
							<option value="">全部</option>
                            <option v-for="(row,index) in estate_list" v-bind:value="index" :key="index">{{row}}</option>
						</select>
					</div>
				</div>
			</div> -->
      </div>
      <div class="col-md-6 col-lg-6">
        <div class="form-horizontal">
          <!-- <div class="form-group">
					<label class="col-md-4 col-sm-2 control-label text-left">审核状态：</label>
					<div class="col-md-8 col-sm-10">
						<select class="form-control" v-model="params.premisesStatus">
							<option value="">全部</option>
							<option value="0">待审核</option>
							<option value="1">审核通过</option>
							<option value="2">审核不通过</option>
						</select>
					</div>
				</div> -->
          <div class="form-group">
            <label class="col-md-4 col-sm-2 control-label">物业类型：</label>
            <div class="col-md-8 col-sm-10">
              <select class="form-control"
                      v-model="params.estateType">
                <option value="">全部</option>
                <option v-for="(row,index) in estate_list"
                        v-bind:value="index"
                        :key="index">{{row}}</option>
              </select>
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label class="col-md-4 col-sm-2 control-label text-left">面积：</label>
            <div class="col-md-8 col-sm-10">
              <select class="form-control"
                      v-model="params.acreage">
                <option value="">全部</option>
                <option value="<=50">50m²以下</option>
                <option value="50-90">50-90m²</option>
                <option value="90-130">90-130m²</option>
                <option value="130-150">130-150m²</option>
                <option value="150-200">150-200m²</option>
                <option value="200-300">200-300m²</option>
                <option value=">300">300m²以上</option>
              </select>
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
          </div>
        </div>

      </div>
      <div class="col-lg-12 col-md-12"
           style="padding: 0 !important;">
        <div class="col-md-6 col-lg-6">
          <div class="form-horizontal">
            <div class="form-group">
              <label class="col-md-3 col-sm-2 control-label text-left">
                <div style="position: relative;padding-bottom: 10px;">
                  <button type="submit"
                          class="btn screen-submit"
                          style="position: static"
                          @mouseover="mousedown(1)"
                          @mouseout="mouseout(1)"
                          v-on:click="changeSort(1)"
                          v-res="{code:'menu_0004_0001_0004'}">置顶</button>
                  <div id="topTips"
                       style="display: none;position: absolute;right: -40px;top: 33px;color: #ff6600;">置顶楼盘展示位置</div>
                </div>
              </label>
              <div class="col-md-8 col-sm-10">
                <div style="position: relative;padding-bottom: 10px;">
                  <img id="up"
                       src="../../assets/images/up.png"
                       style="width: 30px;height: 30px;margin-top: 5px;"
                       @mouseover="mousedown(2)"
                       @mouseout="mouseout(2)" />
                  <img id="upMouseOver"
                       src="../../assets/images/up_mouseOver.png"
                       style="display: none;width: 30px;height: 30px;margin-top: 5px;"
                       v-on:click="changeSort(2)"
                       @mouseover="mousedown(2)"
                       @mouseout="mouseout(2)" />
                  <img id="down"
                       src="../../assets/images/down.png"
                       style="margin-left: 20px;width: 30px;height: 30px;margin-top: 5px;"
                       @mouseover="mousedown(3)"
                       @mouseout="mouseout(3)" />
                  <img id="downMouseOver"
                       src="../../assets/images/down_mouseOver.png"
                       style="display: none;margin-left: 20px;width: 30px;height: 30px;margin-top: 5px;"
                       v-on:click="changeSort(3)"
                       @mouseover="mousedown(3)"
                       @mouseout="mouseout(3)" />
                  <div id="upTips"
                       style="display: none;position: absolute;left: 0;top: 40px;color: #ff6600;font-size: 14px;font-weight: bold;">上移楼盘展示位置</div>
                  <div id="downTips"
                       style="display: none;position: absolute;left: 55px;top: 40px;color: #ff6600;font-size: 14px;font-weight: bold;">下移楼盘展示位置</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-md-6 col-lg-6">
          <div class="form-horizontal">
            <div class="form-group">
              <div class="col-md-12 col-sm-12">
                <label class="col-md-4 col-sm-2 control-label text-left">
                  <button type="submit"
                          class="btn screen-submit"
                          style="position:static"
                          v-on:click="toNewPremisesAdd"
                          v-res="{code:'menu_0004_0001_0001'}">新增合作楼盘</button>
                </label>
                <div class="col-md-8 col-sm-10"
                     style="padding-top: 7px;padding-right:0;">
                  <button type="submit"
                          class="btn screen-submit"
                          style="position:static;margin-left:-15px;"
                          v-on:click="batchDistributePremises"
                          v-res="{code:'menu_0004_0001_0002'}">批量指定分销商</button>
                  <button type="submit"
                          class="btn screen-submit"
                          style="position:static;margin-left:10px;background-color: #3399cc;"
                          v-on:click="list(1)">查询</button>
                  <button type="submit"
                          class="btn screen-submit"
                          style="position:static;margin-left:10px;background-color: #cccccc;"
                          v-on:click="clearParam()"
                          v-res="{code:'menu_0004_0001_0003'}">清空</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="table-responsive report-table">
      <div class="tableTips"><img src="../../assets/images/book.svg">驻场人员中，被设为案场热线的人员为蓝色，其他为普通驻场人员</div>
      <div style="clear: both;"></div>
      <Table stripe
             border
             ref="premisesTable"
             :columns="tableConfig"
             :data="premisesList"
             @on-selection-change="onSelectionChange"></Table>
    </div>
    <div id="laypage_premises"></div>

    <Modal v-model="explainModal"
           width="900">
      <p slot="header"
         style="color:#000;text-align:center">
        <span>保护时间节点说明</span>
      </p>
      <div class="timelineModal"
           style="text-align:center;height: 300px;padding-top:30px;width:800px;padding-left: 60px;">
        <div style="display:flex;position: relative;">
          <div class="horizontalLine"
               :class="{'o-border-color':explainFlag==1}"></div>
          <div class="dot"
               :class="{'o-border-color':explainFlag==1}"><span :class="{'o-color':explainFlag==1}">接触客户</span></div>
          <div class="horizontalLine"
               :class="{'o-border-color':explainFlag==1}"></div>
          <div class="dot"
               :class="{'o-border-color':explainFlag==1 || explainFlag==2}"><span :class="{'o-color':explainFlag==1 || explainFlag==2}">报备客户</span></div>
          <div class="horizontalLine"
               :class="{'o-border-color':explainFlag==2}"></div>
          <div class="dot"
               :class="{'o-border-color':explainFlag==2}"><span :class="{'o-color':explainFlag==2}">客户到访</span></div>
          <div class="horizontalLine-half"
               :class="{'o-border-color':explainFlag==2}"></div>
          <div class="horizontalLine-half"
               :class="{'o-border-color':explainFlag==3}"></div>
          <div class="dot"
               :class="{'o-border-color':explainFlag==3}"><span :class="{'o-color':explainFlag==3}">交易签约</span></div>
          <div class="horizontalLine"
               :class="{'o-border-color':explainFlag==3}"></div>
          <div class="verticalLine1"
               :class="{'o-b-color':explainFlag==1}"></div>
          <div class="verticalLine2"
               :class="{'o-b-color':explainFlag==2}"></div>
          <div class="verticalLine3"
               :class="{'o-b-color':explainFlag==3}"></div>
          <div class="itemText1"
               :class="{'o-b-color':explainFlag==1}">最短报备时间限制</div>
          <div class="itemText2"
               :class="{'o-b-color':explainFlag==2}">到访延长时间限制</div>
          <div class="itemText3"
               :class="{'o-b-color':explainFlag==3}">交易延长时间限制</div>
        </div>
        <div class="tips1"
             v-if="explainFlag==1">
          限制<span class="o-color">报备时间</span>距离<span class="o-color">预计到访时间</span>的<span class="o-color">最少提前时间量</span>，短于这个时<br />
          间量将不能进行常规报备，需要带看到访后由驻场人员代报备
        </div>
        <div class="tips2"
             v-if="explainFlag==2">
          允许<span class="o-color">预计到访时间</span>延后的<span class="o-color">最大时间量</span>，超过这个时间还未到访的<br />客户将<span class="o-color">自动转为为无效客户</span>
        </div>
        <div class="tips3"
             v-if="explainFlag==3">
          <span class="o-color">确认到访后</span>，在此规定时间内，未能进入下个交易环节的客户将<br /><span class="o-color">自动转为无效客户</span>，不填写默认设置为7天
        </div>
      </div>
      <div slot="footer">
      </div>
    </Modal>

    <addAuditModal v-bind:auditModal="auditInfo"
                   v-on:saveAuditListener='saveAuditReturn'></addAuditModal>
    <addSaleModal v-bind:saleModal="saleInfo"
                  v-on:saveAuditListener='saveAuditReturn'></addSaleModal>
    <addDistributeModal v-bind:distributeModal="distributeInfo"
                        v-on:saveAuditListener='saveAuditReturn'></addDistributeModal>
    <batchAddDistributeModal v-bind:distributeModal="distributeInfos"
                             v-on:saveAuditListener='saveAuditReturn'></batchAddDistributeModal>
    <reportModelModal v-bind:reportModelModal="reportModel"></reportModelModal>
    <newPremisesAddModal ref="newPremisesAddModalData"
                         v-bind:premisesMapAddress="premisesMapAddress"
                         @newPremisesAddListener='saveAuditReturn'
                         @openMapModal="openMapModal"></newPremisesAddModal>
    <newPremisesEditModal ref="newPremisesEditModalData"
                          v-bind:newPremisesEditModalData="auditInfo"
                          v-bind:premisesMapAddress="premisesMapAddress"
                          v-on:newPremisesEditListener='saveAuditReturn'
                          @openMapModal="openMapModal"></newPremisesEditModal>
    <addAddress v-bind:premiseAddressInfo="premiseAddressInfo"
                @savePremiseAddress='savePremiseAddress'></addAddress>
    <selectUserModal></selectUserModal>
    <linkM2Modal></linkM2Modal>
    <referrer-modal :premises-id="premisesId"
                    :referrer-title="referrerTitle"
                    ref="referrerModal"
                    @setReferrerListener='saveAuditReturn'></referrer-modal>
    <adviser-modal :premises-id="premisesId"
                   :referrer-title="referrerTitle"
                   ref="adviserModal"
                   @setAdviserListener='saveAuditReturn'></adviser-modal>
    <!-- 设置楼盘驻守人 -->
    <el-dialog ref="changeDialog"
               width="940px"
               title="设置楼盘驻守人"
               :visible.sync="changeManagerVisible"
               :before-close="changeManagerModalClose">
      <selfDeptUserTable ref="selfDeptUserTable"
                         v-if="changeManagerVisible"
                         @modalClose="changeManagerModalClose"
                         :is-only="true"
                         :user-list="tableData"
                         :premisesId="premisesId"></selfDeptUserTable>
    </el-dialog>
  </div>
</template>
<script>
import selfDeptUserTable from "../org/components/selfDeptUserForPremises.vue";
import addAuditModal from "./premisesAudit.vue";
import addSaleModal from "./premisesSaleStatus.vue";
import addDistributeModal from "./premisesDistribute.vue";
import batchAddDistributeModal from "./batchPremisesDistribute.vue";
import dataTable from "../../constants/tableConfig.js";
import reportModelModal from "./reportModel.vue";
import newPremisesAddModal from "./newPremisesAdd.vue";
import newPremisesEditModal from "./newPremisesEdit.vue";
import addAddress from "./addAddress.vue";
import selectUserModal from "./selectUserModal.vue";
import linkM2Modal from "./linkM2Modal.vue";
import ReferrerModal from "./components/ReferrerModal.vue";
import AdviserModal from "./components/AdviserModal.vue";
import { API, Log, Utils, Service } from "../../js/base";
export default {
  data() {
    return {
      changeManagerVisible: false,
      activeName: "1",
      params: {
        pageNo: 1,
        pageSize: 10,
        name: "",
        provinceId: "",
        cityId: "",
        areaId: "",
        estateType: "",
        premisesStatus: 1,
        acreage: "",
        domain: window.location.href,
        premisesSaleStatus: [1] // 初始加载在售楼盘
      },
      tableData: [],
      choosePremisesUserVisible: false,
      bindPremisesIds: [],
      premisesIds: [],
      premisesList: [],
      estate_list: [],
      premises_province_list: [],
      premises_city_list: [],
      premises_area_list: [],
      distributeInfo: {
        premisesId: "",
        time: new Date().getTime()
      },
      distributeInfos: {
        premisesId: [],
        premisesStatus: "",
        time: new Date().getTime()
      },
      auditInfo: {
        premisesId: "",
        time: new Date().getTime()
      },
      saleInfo: {
        premisesId: "",
        saleStatus: ""
      },
      tableConfig: [],
      show: true,
      dataTotal: "",
      totalPage: "",
      currIndex: "",
      loadObj: null,
      reportModel: { premisesId: "", modelColumn: "" },
      userAuthResources: window.localStorage.getItem("userAuthResources"),
      premisesTypeCount: {
        onSaleCount: 0,
        forSaleCount: 0,
        beCheckCount: 0,
        sellOutCount: 0,
        lowerShelfCount: 0,
        checkFailCount: 0
      },
      explainModal: false,
      explainFlag: "1",
      settingReferrerModal: false,
      premisesId: null,
      premiseAddressInfo: {},
      premisesMapAddress: {
        premisesAddress: "",
        lng: "",
        lat: ""
      },
      referrerTitle: ""
    };
  },
  components: {
    addAddress,
    newPremisesAddModal,
    newPremisesEditModal,
    addAuditModal,
    addSaleModal,
    addDistributeModal,
    batchAddDistributeModal,
    dataTable,
    reportModelModal,
    selectUserModal,
    linkM2Modal,
    ReferrerModal,
    AdviserModal,
    selfDeptUserTable
  },
  mounted: function () {
    // 初始化加载
    this.list(0);
    this.estateList();
    this.provinceList();
    dataTable.config.table = this;
    this.tableConfig = dataTable.config.premisesColumns;
  },
  // beforeRouteEnter(to, from, next) {
  //   //设置下一个路由的meta（即首页）
  //   if(from.path.indexOf('/premisesDetail/')!==-1){
  //     next(vm=>{
  //     vm.params=vm.$store.getters.getPremisesData.params
  //     vm.activeName=vm.$store.getters.getPremisesData.activeName
  //     vm.list(0)
  //     vm.estateList()
  //     vm.provinceList()
  //     dataTable.config.table = vm
  //     vm.tableConfig = dataTable.config.premisesColumns
  //     })
  //   }else{
  //     next(vm=>{
  //     vm.list(0)
  //     vm.estateList()
  //     vm.provinceList()
  //     dataTable.config.table = vm
  //     vm.tableConfig = dataTable.config.premisesColumns})
  //   }
  // },
  methods: {
    premisesTypeCountList() {
      var body = {};
      body.params = {};
      var url = this.utilHelper.apiUrl + "/api/premisesTypeCount.do";
      this.$http.post(url, body).then((response) => {
        var body = response.body.resData;
        if (body.result == "1") {
          this.premisesTypeCount = body;
        } else {
          console.log(response);
        }
      });
    },
    changeMenuSelect(name) {
      this.activeName = name;
      switch (name) {
        case "1": // 在售楼盘
          this.params.premisesSaleStatus = [1];
          this.params.premisesStatus = 1;
          break;
        case "2": // 待售楼盘
          this.params.premisesSaleStatus = [0];
          this.params.premisesStatus = 1;
          break;
        case "3": // 待审核
          this.params.premisesSaleStatus = null;
          this.params.premisesStatus = 0;
          break;
        case "4": // 售罄楼盘
          this.params.premisesSaleStatus = [2];
          this.params.premisesStatus = 1;
          break;
        case "5": // 下架楼盘
          this.params.premisesSaleStatus = [3];
          this.params.premisesStatus = 1;
          break;
        case "6": // 审核不通过
          this.params.premisesSaleStatus = null;
          this.params.premisesStatus = 2;
          break;
        default:
          break;
      }
      this.list(1);
    },
    changeSort(flag) {
      var _self = this;
      if (_self.premisesIds.length == 0) {
        layer.msg("请选择操作数据", { icon: 7, time: 2000 });
        return;
      }
      /* if(_self.params.pageNo == 1 && _self.currIndex == 1 && (flag == 1 || flag == 2)) {
					//是否最上方
					layer.msg('楼盘已被移至列表的最上方', { icon: 7, time: 2000 });
					return;
				} */
      if (
        _self.params.pageNo == 1 &&
        _self.currIndex == 1 &&
        _self.premisesList[_self.currIndex - 1].sequence &&
        _self.premisesList[_self.currIndex - 1].sequence == 1 &&
        (flag == 1 || flag == 2)
      ) {
        // 是否最上方
        layer.msg("楼盘已被移至列表的最上方", { icon: 7, time: 2000 });
        return;
      }
      // 暂时不支持多个上移下移
      if ((flag == 2 || flag == 3) && _self.premisesIds.length > 1) {
        layer.msg("只支持单个楼盘移动", { icon: 7, time: 2000 });
        return;
      }
      if (flag == 1) {
        this.params.pageNo = 1;
      } else if (flag == 2) {
      } else if (flag == 3) {
        if (
          _self.dataTotal &&
          _self.totalPage &&
          _self.totalPage == _self.params.pageNo &&
          _self.dataTotal % _self.params.pageSize == _self.currIndex
        ) {
          // 是否最下方
          layer.msg("楼盘已被移至列表的最下方", {
            icon: 7,
            time: 2000
          });
          return;
        }
      }
      this.loadObj = layer.load();
      this.setPremisesOrder(flag);
    },
    setPremisesOrder(flag) {
      var body = {};
      body.params = { opType: flag, premisesIds: this.premisesIds };
      var url = this.utilHelper.apiUrl + "/api/setPremisesOrder";
      this.$http.post(url, body).then((res) => {
        var body = res.body;
        if (body.result == "1") {
          // 判断当前移动的数据是否为次页的第一个，是则改变页数
          if (this.params.pageNo > 1 && this.currIndex == 1) {
            this.params.pageNo = this.params.pageNo - 1;
            this.currIndex == this.params.pageSize; // 移至最后一个
          }
          // 判断当前移动的数据是否为最后一个，是则改变页数
          if (
            this.params.pageNo < this.totalPage &&
            this.currIndex == this.params.pageSize
          ) {
            this.params.pageNo = this.params.pageNo + 1;
            this.currIndex == 1; // 移至第一个
          }
          this.list("setOrder");
        } else {
          layer.close(this.loadObj);
          layer.msg(body.errorMsg);
        }
      });
    },
    list(type) {
      var _self = this;
      // 判断点查询按钮时，将当前页和条数设置为默认
      if (type == "1") {
        _self.params.pageNo = 1;
        _self.params.pageSize = 10;
      }
      var body = {};
      body.params = _self.params;
      var url = this.utilHelper.apiUrl + "/api/getPremisesPage.do";
      _self.$http.post(url, body).then((response) => {
        _self.premisesTypeCountList();
        if (type && type == "setOrder") {
          layer.close(this.loadObj);
          layer.msg("操作成功");
        }
        var body = response.body.resData;
        if (body.result == "1") {
          var resData = body.getPremisesPage;
          var totalPages = resData.totalPages;
          var total = resData.total;
          var current = resData.pageNumber;
          _self.dataTotal = total;
          _self.totalPage = totalPages;
          _self.premisesList = resData.rows;
          for (var i = 0; i < _self.premisesList.length; i++) {
            _self.premisesList[i].averagePrice = _self.setAveragePrice(
              _self.premisesList[i].averagePrice
            );
            _self.premisesList[i].index = i + 1;
            if (type == "setOrder" && _self.premisesIds.length > 0) {
              for (var j = 0; j < _self.premisesIds.length; j++) {
                var premisesId = _self.premisesIds[j];
                if (premisesId == _self.premisesList[i].id) {
                  _self.premisesList[i]._checked = true;
                  if (j == 0) {
                    _self.currIndex = _self.premisesList[i].index;
                  }
                }
              }
            }
          }
          if (totalPages >= 0) {
            layui.laypage.render({
              elem: $("#laypage_premises"), // 容器。值支持id名、原生dom对象，jquery对象,
              limit: _self.params.pageSize,
              curr: current,
              count: total,
              theme: "#f87242;", // 皮肤
              first: "首页", // 若不显示，设置false即可
              last: "尾页", // 若不显示，设置false即可
              prev: "上一页", // 若不显示，设置false即可
              next: "下一页", // 若不显示，设置false即可
              layout: ["prev", "page", "next", "skip", "count"],
              jump: function (obj, first) {
                if (!first) {
                  _self.params.pageNo = obj.curr;
                  _self.list(0);
                }
              }
            });
          } else {
            laypage.render({
              elem: $("#laypage_premises"),
              count: 0
            });
          }
        } else {
          console.log(response);
        }
      });
    },
    estateList: function () {
      var _self = this;
      var body = {};
      body.params = {};
      var url = _self.utilHelper.apiUrl + "/common/getEnum/EstateTypeEnum";
      _self.$http.get(url, body).then((response) => {
        var body = response.body.data;
        _self.estate_list = body;
      });
    },
    provinceList: function () {
      var _self = this;
      var body = {};
      body.params = {};
      var url = _self.utilHelper.apiUrl + "/api/getProvince.do";
      _self.$http.post(url, body).then((response) => {
        var resData = response.body.resData;
        if (resData.result == "1") {
          _self.premises_province_list = resData.areaList;
        }
      });
    },
    getCity: function () {
      var _self = this;
      var provinceId = $("#province").val();
      if (!provinceId) {
        provinceId = 0;
      }
      var body = {};
      body.params = {
        areaId: provinceId
      };
      var url = _self.utilHelper.apiUrl + "/api/getCity.do";
      _self.$http.post(url, body).then((response) => {
        var resData = response.body.resData;
        if (
          resData.result == "1" ||
          (resData.areaList && resData.areaList.length > 0)
        ) {
          _self.premises_city_list = resData.areaList;
          _self.params.cityId = "";
          _self.params.areaId = "";
          _self.premises_area_list = [];
        }
      });
    },
    getArea: function () {
      var _self = this;
      var cityId = $("#city").val();
      if (!cityId) {
        cityId = 0;
      }
      var body = {};
      body.params = {
        areaId: cityId
      };
      var url = _self.utilHelper.apiUrl + "/api/getArea.do";
      _self.$http.post(url, body).then((response) => {
        var resData = response.body.resData;
        if (resData.result == "1") {
          _self.params.areaId = "";
          _self.premises_area_list = resData.areaList;
        }
      });
    },
    toNewPremisesAdd() {
      this.premisesMapAddress = { premisesAddress: "", lng: "", lat: "" };
      // 初始化
      this.initParamsNewPremisesAddOrEdit();
      $("#newPremisesAddModal").modal({
        backdrop: "static",
        keyboard: false,
        show: true
      });
    },
    initParamsNewPremisesAddOrEdit() {
      this.$refs.newPremisesAddModalData.initParams();
      this.$refs.newPremisesEditModalData.initParams();
      this.$store.commit("set_selectUserDataType", "");
      this.$store.commit("set_selectUserDataChiefName", "");
      this.$store.commit("set_selectUserDataChiefPhone", "");
      this.$store.commit("set_selectUserDataManagerName", "");
      this.$store.commit("set_selectUserDataManagerPhone", "");
    },
    toPremisesAudit: function (premisesId) {
      // 审核
      this.auditInfo.premisesId = premisesId;
      $("#addAuditModal").modal("show");
    },
    toPremisesSaleStatus: function (premisesId, saleStatus) {
      // 销售状态变更
      this.saleInfo.premisesId = premisesId;
      this.saleInfo.saleStatus = saleStatus;
      $("#addSaleModal").modal("show");
    },
    changeShelvesStatus: function (premisesId, shelvesStatus) {
      var _self = this;
      var operationMsg = "上架";
      if (shelvesStatus == 1) {
        operationMsg = "下架";
        shelvesStatus = "0";
      } else {
        shelvesStatus = "1";
      }
      layer.confirm(
        "您是否确定要" + operationMsg + "该楼盘？",
        {
          skin: "layui-layer-DarkOrange", // 样式类名
          btn: ["确定", "取消"]
        },
        function () {
          var body = {};
          body.params = {
            id: premisesId,
            shelvesStatus: shelvesStatus
          };
          var url = _self.utilHelper.apiUrl + "/api/changeShelvesStatus";
          _self.$http.post(url, body).then(
            (response) => {
              var resData = response.body.resData;
              if (resData.result == "1") {
                layer.msg(operationMsg + "成功");
                _self.list(0);
              } else {
                layer.msg(operationMsg + "失败");
              }
            },
            (response) => {
              layer.msg(operationMsg + "失败");
            }
          );
        }
      );
    },
    deletePremises: function (premisesId) {
      var _self = this;
      layer.confirm(
        "删除后此楼盘将不在此列表、分销PC、分销助手楼盘列表中展示，请确认是否删除？",
        {
          skin: "layui-layer-DarkOrange", // 样式类名
          btn: ["确定", "取消"]
        },
        function () {
          layer.closeAll("dialog");
          var body = {};
          body.params = {
            id: premisesId
          };
          var url = _self.utilHelper.apiUrl + "/api/deletePremises.do";
          _self.$http.post(url, body).then((response) => {
            var resData = response.body.resData;
            if (resData.result == "1") {
              layer.msg("删除成功");
              _self.list();
            } else {
              layer.msg("删除失败");
            }
          });
        }
      );
    },
    // 打开地图选址的弹窗
    openMapModal(data) {
      // console.log(9999, data);
      this.premiseAddressInfo = data;
      $("#addPremiseAddress").modal({
        backdrop: "static",
        keyboard: false,
        show: true
      });
    },
    // 确定地图选址的地址和经纬度
    savePremiseAddress(data) {
      // console.log(99, data);
      this.premiseAddressInfo = data;
      this.premisesMapAddress = data;
    },
    toPremisesEdit(premisesId) {
      this.auditInfo.premisesId = premisesId;
      this.auditInfo.time = new Date().getTime();
      this.initParamsNewPremisesAddOrEdit();
      $("#newPremisesEditModal").modal({
        backdrop: "static",
        keyboard: false,
        show: true
      });
    },
    toPremisesDetail(premisesId) {
      // 跳转楼盘详情,新打开一个而窗口
      let router = this.$router.resolve({
        path: "/premisesDetail/" + premisesId
      });
      window.open(router.href, "_blank");
      // this.$store.commit('setPremisesData',{activeName:this.activeName,params:this.params})
      // this.$router.push({
      //   path: '/premisesDetail/' + premisesId
      // })
    },
    saveAuditReturn() {
      this.premisesIds = [];
      this.list();
    },
    // 指定分销商
    toDistributePremises: function (premisesId) {
      this.distributeInfo.premisesId = premisesId;
      this.distributeInfo.time = new Date().getTime();
      $("#addDistributeModal").modal("show");
    },
    toPremisesAdd() {
      // 跳转楼盘新增
      this.$router.push({
        path: "/premisesAdd"
      });
    },
    onSelectionChange: function (arr) {
      let _self = this;
      _self.premisesIds = [];
      if (arr && arr.length > 0) {
        // 获取当前选中的排序
        _self.currIndex = arr[0].index;
        for (var i = 0; i < arr.length; i++) {
          _self.premisesIds.push(arr[i].id);
        }
      }
    },
    batchDistributePremises: function () {
      let _self = this;
      if (_self.premisesIds.length == 0) {
        layer.msg("请选择需要指定的楼盘");
        return;
      }
      $("#batchAddDistributeModal").modal("show");
      this.distributeInfos.premisesId = _self.premisesIds;
      this.distributeInfos.premisesStatus = this.params.premisesStatus;
      this.distributeInfos.premisesSaleStatus =
        this.params.premisesSaleStatus != null
          ? this.params.premisesSaleStatus[0]
          : "-1";
    },
    // 设置均价
    setAveragePrice(averagePrice) {
      if (averagePrice) {
        let price = averagePrice.split(",");
        if (price.length > 1) {
          if (price[0] && price[1]) {
            averagePrice = price[0] + " 至 " + price[1];
          } else if (price[0]) {
            averagePrice = price[0];
          } else if (price[1]) {
            averagePrice = price[1];
          }
        }
      }
      return averagePrice;
    },
    mousedown(flag) {
      if (flag == 1) {
        $("#topTips").show();
      } else if (flag == 2) {
        $("#up").hide();
        $("#upMouseOver").show();
        $("#upTips").show();
      } else if (flag == 3) {
        $("#down").hide();
        $("#downMouseOver").show();
        $("#downTips").show();
      }
    },
    mouseout(flag) {
      if (flag == 1) {
        $("#topTips").hide();
      } else if (flag == 2) {
        $("#up").show();
        $("#upMouseOver").hide();
        $("#upTips").hide();
      } else if (flag == 3) {
        $("#down").show();
        $("#downMouseOver").hide();
        $("#downTips").hide();
      }
    },
    clearParam() {
      this.params.name = "";
      this.params.provinceId = "";
      this.params.cityId = "";
      this.params.areaId = "";
      this.params.estateType = "";
      this.params.acreage = "";
    },
    showReportModel(id) {
      var _self = this;
      _self.reportModel.premisesId = id;
      $("#reportModelModal").modal("show");
    },
    setProtectTime(time, type) {
      if (!time || !type) {
        return "";
      }
      if (type == "1") {
        return time / 1440 + "天";
      } else if (type == "2") {
        return time / 60 + "小时";
      } else if (type == "3") {
        return time + "分钟";
      }
      return "";
    },
    setMainPush(id, mainPush) {
      var _self = this;
      if (!mainPush) {
        mainPush = 2;
      } else if (mainPush == 1) {
        mainPush = 2;
      } else if (mainPush == 2) {
        mainPush = 1;
      }
      let msg =
        mainPush == 1 ? "您是否确定取消主推该楼盘？" : "您是否确定主推该楼盘？";
      let resultMsg = mainPush == 1 ? "取消主推成功" : "设置主推成功";
      layer.confirm(
        msg,
        {
          btn: ["确定", "取消"] // 按钮
        },
        function () {
          let url = _self.utilHelper.apiUrl + "/api/setMainPushPremises";
          let body = {};
          body.params = {
            premisesId: id,
            mainPush: mainPush
          };
          _self.$http.post(url, body).then(
            (response) => {
              if (response.body.result == "1") {
                layer.msg(resultMsg);
                // 关闭确认框
                _self.list();
              }
            },
            (response) => {
              layer.msg("设置失败");
            }
          );
        },
        function () {}
      );
    },
    showExplain(flag) {
      this.explainModal = true;
      this.explainFlag = flag;
    },
    showPremisesStatus(remark) {
      layer.alert(remark, {
        title: "审核不通过原因"
      });
    },
    setReferrer(info) {
      const name = info.name ? info.name : "";
      this.referrerTitle = `为“${name}”设置项目推荐人`;
      $("#settingReferrerModal").modal("show");
      this.$refs.referrerModal.getRecommendList(info.id);
      this.premisesId = info.id;
    },
    setDefend(info) {
      const _this = this;
      _this.tableData = [];
      _this.premisesId = info.id;
      if (!info.id) return;
      let index = -1;
      Service.Premise.getPartnerByPremisesList(info.id, this).then((list) => {
        if (list && list.length) {
          list.forEach((item) => {
            _this.tableData.push(item);
          });
          _this.changeManagerVisible = true;
        }
      });
    },
    changeManagerModalClose() {
      this.changeManagerVisible = false;
    },
    getSaveData() {
      const _this = this;
      let tableData = JSON.parse(JSON.stringify(_this.tableData));
      this.chooseUserVisible = false;
      const userItemList = this.$refs.selfDeptUserTable.$refs.userItem;
      let userInfoList = [];
      if (userItemList && userItemList.length) {
        userItemList.forEach((item) => {
          if (item.selected && item.userInfo) {
            // item为vue实例，select是组件实例属性，标记是否选中
            item.userInfo.recommenderId = item.userInfo.id;
            item.userInfo.selected = item.selected;
            userInfoList.push(item.userInfo);
          } else if (!item.selected) {
            // 原有选中，但有此次取消的
            let index = tableData.findIndex(
              (i) => i.recommenderId === item.userInfo.id
            );
            if (index > -1) {
              tableData.splice(index, 1);
            }
          }
        });
        let tempList = [];
        if (tableData.length) {
          // 有值去重
          tableData = [...tableData, ...userInfoList];
          let obj = {},
            tempKey = "";
          tableData.forEach((item) => {
            tempKey = "key-" + item.recommenderId;
            if (!obj[tempKey]) {
              tempList.push(item);
              obj[tempKey] = true; // 标记该值已存在
            }
          });
        } else {
          tempList = userInfoList;
        }
        this.tableData = [...tempList];
      }
    },
    /**
     * 获取楼盘驻守人列表
     */
    getPartnerByPremisesList(id) {
      const _this = this;
      _this.tableData = [];
      //const tmpList = []
      if (!id) return;
      let index = -1;
      Service.Premise.getPartnerByPremisesList(id, this)
        .then((list) => {
          _this.getReferrerLoading = false;
          if (list && list.length) {
            list.forEach((item) => {
              item.partnerId = item.partnerId;
              item.accountName = item.accountName;
              _this.tableData.push(item);
            });
          }
        })
        .catch((e) => {
          _this.getReferrerLoading = false;
        });
    },
    choosePremisesUserModalClose() {
      this.choosePremisesUserVisible = false;
      this.premisesIds = [];
      this.list();
    },
    setAdviser(info) {
      const name = info.name ? info.name : "";
      this.referrerTitle = `为“${name}”设置置业顾问`;
      $("#adviserModal").modal("show");
      this.$refs.adviserModal.getAdviserList(info.id);
      this.premisesId = info.id;
    }
  }
};
</script>
<style type="text/css">
.setting-referrer .dialog__header {
  border-bottom: 1px solid #ccc;
}
.premiseDropdown {
  max-height: 400px;
}
</style>
<style scoped lang="less">
.ivu-menu .gray-color {
  color: #999999 !important;
}
.ivu-menu .ivu-menu-item-active,
.ivu-menu .ivu-menu-item-selected {
  color: #f87242 !important;
}

.timelineModal .dot {
  border: 2px solid #cfcfcf;
  width: 15px;
  height: 15px;
  border-radius: 50px;
  background: white;
  margin: auto;
  margin-bottom: -7px;
  position: relative;
}
.timelineModal .dot span {
  position: absolute;
  width: 100px;
  left: -17px;
  top: 20px;
  display: inline-flex;
  font-size: 15px;
  font-weight: bold;
}
.timelineModal .item {
  flex: 1;
  display: flex;
  border-bottom: 1px solid #ddd;
  margin-top: -10px;
}
.timelineModal .horizontalLine {
  flex: 1;
  display: flex;
  border-bottom: 1px solid #ddd;
}
.timelineModal .horizontalLine-half {
  flex: 0.5;
  display: flex;
  border-bottom: 1px solid #ddd;
}
.timelineModal .verticalLine1 {
  width: 1px;
  height: 100px;
  border: 1px solid #ddd;
  position: absolute;
  top: 10px;
  left: 220px;
}
.timelineModal .verticalLine2 {
  width: 1px;
  height: 100px;
  border: 1px solid #ddd;
  position: absolute;
  top: 10px;
  right: 245px;
}
.timelineModal .verticalLine3 {
  width: 1px;
  height: 100px;
  border: 1px solid #ddd;
  position: absolute;
  top: 10px;
  right: 70px;
}
.timelineModal .itemText1 {
  position: absolute;
  width: 130px;
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 20px;
  line-height: 36px;
  text-align: center;
  font-size: 13px;
  color: #999;
  top: 110px;
  left: 160px;
}
.timelineModal .itemText2 {
  position: absolute;
  width: 130px;
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 20px;
  line-height: 36px;
  text-align: center;
  font-size: 13px;
  color: #999;
  top: 110px;
  right: 175px;
}
.timelineModal .itemText3 {
  position: absolute;
  width: 130px;
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 20px;
  line-height: 36px;
  text-align: center;
  font-size: 13px;
  color: #999;
  top: 110px;
  right: 5px;
}
.timelineModal .tips1 {
  position: absolute;
  top: 270px;
  left: 220px;
  color: #999;
}
.timelineModal .tips2 {
  position: absolute;
  top: 270px;
  right: 70px;
  text-align: left;
  color: #999;
}
.timelineModal .tips3 {
  position: absolute;
  top: 270px;
  right: 50px;
  text-align: right;
  color: #999;
}
.tableTips {
  float: right;
  line-height: 38px;
  color: #333;
}
.tableTips img {
  width: 20px;
  height: 20px;
  margin-bottom: 3px;
  margin-right: 3px;
}
</style>
